package com.tmtc.utils.duiba;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tmtc.controller.appAPI.DuiBaController;

public class SignTool {

	private static Logger logger = LoggerFactory.getLogger(DuiBaController.class);

	@SuppressWarnings("unchecked")
	public static boolean signVerify(String appSecret, HttpServletRequest request) {
		Map<String, String[]> map = request.getParameterMap();
		Map<String, String> data = new HashMap<String, String>();
		for (String key : map.keySet()) {
			data.put(key, map.get(key)[0]);
		}
		return signVerify(appSecret, data);
	}

	public static boolean signVerify(String appSecret, Map<String, String> params) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("appSecret", appSecret);

		for (String key : params.keySet()) {

			try {
				if (!key.equals("sign")) {
					map.put(key, new String(params.get(key).getBytes("ISO8859-1"), "utf-8"));
//					if (key.equals("description")) {
//						map.put(key, new String(params.get(key).getBytes("ISO8859-1"), "utf-8"));
//					} else if (key.equals("params")) {
//						map.put(key, new String(params.get(key).getBytes("ISO8859-1"), "utf-8"));
//					} else if (key.equals("errorMessage")) {
//						map.put(key, new String(params.get(key).getBytes("ISO8859-1"), "utf-8"));
//					} else {
//						map.put(key, params.get(key));
//					}
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			try {
				logger.info(key.toString() + "----------------" + new String(params.get(key).getBytes("ISO8859-1"), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		String sign = sign(map);
		if (sign.equals(params.get("sign"))) {
			return true;
		}
		return false;
	}

	private static String toHexValue(byte[] messageDigest) {
		if (messageDigest == null)
			return "";
		StringBuilder hexValue = new StringBuilder();
		for (byte aMessageDigest : messageDigest) {
			int val = 0xFF & aMessageDigest;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	/**
	 * 
	 * @param params
	 * @return
	 */
	public static String sign(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		String string = "";
		for (String s : keys) {
			string += params.get(s);
		}
		String sign = "";
		try {
			sign = toHexValue(encryptMD5(string.getBytes(Charset.forName("utf-8"))));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("md5 error");
		}
		return sign;
	}

	private static byte[] encryptMD5(byte[] data) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(data);
		return md5.digest();
	}

//	public static void main(String[] args) {
////		String appKey = "key";
//		String appSecret = "secret";
//
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("appKey", "4Va87rouTa9J5VRe6F4NZCAwHHQ8");
//		params.put("appSecret", "5iiiLr8E8Vo8mkAtRj2y7cQSrSg");
//		params.put("uid", "123");
//		params.put("paramsTest95", "95");
//		params.put("orderNum", "order-for-test-1447650147557");
//		params.put("credits", "500");
//		params.put("params", "admin@duiba.com:åå§");
//		params.put("type", "alipay");
//		params.put("ip", "192.168.1.100");
//		params.put("timestamp", "1447650147557");
//		params.put("waitAudit", "true");
//		params.put("actualPrice", "500");
//		params.put("description", "æ¯ä»å®è´¦å·ï¼admin@duiba.com(åå§) è½¬è´¦åå¼ï¼5å");
//		params.put("facePrice", "500");
//
//		String sign = sign(params);
//
//		params.put("sign", sign);
//
////		System.out.println(signVerify(appSecret, params));
//
//	}
}
